#include <stdio.h>
#include <stdlib.h>

#define FNAME "/tmp/out"



struct node_st
{
	char data;
	struct node_st *l,*r;

};

int insert(struct node_st **root,int data)
{
	struct node_st *node;
	if((*root) == NULL)
	{
		node = malloc(sizeof(*node));
		if (node == NULL)
			return -1;

		node->data = data;
		node->l = NULL;
		node->r = NULL;

		(*root) = node;
		return 0;
	}
	

	if(data <= (*root)->data)/*左孩子*/
		return insert(&(*root)->l,data);
	return insert(&(*root)->r,data);/*右孩子*/

}

static void draw_(struct node_st *root,int level)
{
	int i = 0;
	if (root == NULL)
		return ;

	draw_(root->r,level+1);
	for (i = 0;i< level;i++)
		printf("	");
	printf("%c\n",root->data);
	draw_(root->l,level+1);
}

void draw(struct node_st *root)
{
	draw_(root,0);
	printf("\n\n");
}

void destroy(struct node_st *root)
{
	if (root == NULL)
		return ;
	destroy(root->r);
	destroy(root->l);
	free(root);
}
#if 0
int save_(struct node_st *root,FILE *fp)
{
	fputc('(',fp);
	/*if error*/

	if(root ==  NULL)//空结点
	{
		fputc(')',fp);
		return 0;
	}

	fputc(root->data,fp);

	save_(root->l,fp);
	save_(root->r,fp);

	fputc(')',fp);
	/*if error*/
	return 0;
}

int save(struct node_st *root,const char *path)
{
	FILE *fp;
	fp = fopen(path,"w");
	if (fp == NULL)
		return -1;

	save_(tree,fp);
	return 0;
}
#endif

struct node_st *load_(FILE *fp)
{
	int c;
	struct node_st *root;
	c = fgetc(fp);
	/*if error*/
	if(c != '(')//开头不是 (
	{
		fprintf(stderr,"fgetc():error.\n");
		exit(1);
	}
	c = fgetc(fp);

	if (c == ')')//下一个是) 即是空结点
		return NULL;

	root = malloc(sizeof(*root));
	if (root == NULL)
		exit(1);

	root->data = c;
	root->l = load_(fp);
	root->r = load_(fp);
	fgetc(fp);
	/*if error*/

	return root;
}

struct node_st *load(const char *path)
{
	FILE *fp;
	struct node_st *root;
	fp = fopen(path,"r");

	if (fp == NULL)
		return NULL;

	root = load_(fp);
	fclose(fp);

	return root;
}

int main()
{
	struct node_st *root;

	root=load(FNAME);

	draw(root);
	exit(0);
}


